'''
Created on Dec 15, 2010

@author: mwicat
'''

import os, sys, socket
from os import path
import core
import imp
import logging.config
import logging

logger = logging.getLogger(__name__)



def create_socket_stream(host, port):
    sock = socket.socket()
    sock.connect((host, port))
    stream = sock.makefile()
    return stream

def init_socket_logging(config):
    try:
        stream = create_socket_stream(config.LOG_SERVER, config.LOG_PORT)
    except socket.error:
        logger.error('Log server not available. Logging to standard error.')
        stream = sys.stderr
    logging.basicConfig(level=logging.DEBUG, stream=stream, format=config.LOG_FORMAT)


def get_data_dir():
    if core.on_symbian():
        import e32
        drive = 'C:\\' if e32.in_emulator() else 'E:\\'
        dir = path.join(drive, 'data', 'sniffy')
    else:
        dir = path.join('..', 'data')
    return dir

def go_background():
    if core.on_symbian():
        import appswitch
        appswitch.switch_to_fg(u'Menu')

def load_config(name):
    fn = '%s.py' % name
    return imp.load_source(name, get_resource_path(fn))

def get_resource_path(name):
    path = os.path.join(data_dir, name)
    return path


def init_logging():
    path = os.path.join(data_dir, 'logging.conf')
    logging.config.fileConfig(path)

data_dir = get_data_dir()

